import RPi.GPIO as GPIO
import time

class Motor(object):
    def __init__(self,pwma=18,ain1=22,ain2=27,pwmb=23,bin1=25,bin2=24):
        self.PWMA = pwma
        self.AIN1 = ain1
        self.AIN2 = ain2
        self.PWMB = pwmb
        self.BIN1 = bin1
        self.BIN2 = bin2
        
    #初始化
    def init(self):
        GPIO.setup(self.AIN2,GPIO.OUT)
        GPIO.setup(self.AIN1,GPIO.OUT)
        GPIO.setup(self.PWMA,GPIO.OUT)

        GPIO.setup(self.BIN1,GPIO.OUT)
        GPIO.setup(self.BIN2,GPIO.OUT)
        GPIO.setup(self.PWMB,GPIO.OUT)
        
    #启动电机
    def start(self):        
        self.L_Motor= GPIO.PWM(self.PWMA,100)
        self.L_Motor.start(0)
        self.R_Motor = GPIO.PWM(self.PWMB,100)
        self.R_Motor.start(0)
    
    def up(self,speed,t_time):
        self.L_Motor.ChangeDutyCycle(speed)
        GPIO.output(self.AIN2,False)#self.AIN2
        GPIO.output(self.AIN1,True) #self.AIN1

        self.R_Motor.ChangeDutyCycle(speed)
        GPIO.output(self.BIN2,False)#self.BIN2
        GPIO.output(self.BIN1,True) #self.BIN1
        time.sleep(t_time)

    def stop(self,t_time):
        self.L_Motor.ChangeDutyCycle(0)
        GPIO.output(self.AIN2,False)#self.AIN2
        GPIO.output(self.AIN1,False) #self.AIN1

        self.R_Motor.ChangeDutyCycle(0)
        GPIO.output(self.BIN2,False)#self.BIN2
        GPIO.output(self.BIN1,False) #self.BIN1
        time.sleep(t_time)

    def down(self,speed,t_time):
        self.L_Motor.ChangeDutyCycle(speed)
        GPIO.output(self.AIN2,True)#self.AIN2
        GPIO.output(self.AIN1,False) #self.AIN1

        self.R_Motor.ChangeDutyCycle(speed)
        GPIO.output(self.BIN2,True)#self.BIN2
        GPIO.output(self.BIN1,False) #self.BIN1
        time.sleep(t_time)

    def left(self,speed,t_time):
        self.L_Motor.ChangeDutyCycle(speed)
        GPIO.output(self.AIN2,True)#self.AIN2
        GPIO.output(self.AIN1,False) #self.AIN1

        self.R_Motor.ChangeDutyCycle(speed)
        GPIO.output(self.BIN2,False)#self.BIN2
        GPIO.output(self.BIN1,True) #self.BIN1
        time.sleep(t_time)

    def right(self,speed,t_time):
        self.L_Motor.ChangeDutyCycle(speed)
        GPIO.output(self.AIN2,False)#self.AIN2
        GPIO.output(self.AIN1,True) #self.AIN1

        self.R_Motor.ChangeDutyCycle(speed)
        GPIO.output(self.BIN2,True)#self.BIN2
        GPIO.output(self.BIN1,False) #self.BIN1
        time.sleep(t_time)